import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { Form, Row, Col, Input, Radio, Select, Button, Space, Checkbox, message } from "antd";
import Style from "../index.module.less";
import "./index.css";
import { useEffect, useRef, useState } from "react";
import { selectInboundorderDetailByCode, confirmReceipt, getSkuCode } from "../service";
import ConfirmModal from "./ConfirmModal";
import AntdWrapper from "@/components/AntdWrapper";
// 语音播报
import { speak } from "@/utils/utils.jsx";
import mock from "../mock";
const Sider = ({
	data,
	setData,
	warehouseList,
	isShowImg,
	setIsShowImg,
	setImgUrl,
	setImgVisible,
	isBroadcastScanQuantity,
	setIsBroadcastScanQuantity
}) => {
	const [form] = Form.useForm();

	const RefNo = useRef();
	const RefCode = useRef();

	const [visible, setVisible] = useState(false);
		
	//监听键盘事件,阻止默认事件
	useEffect(() => {
		window.addEventListener("keydown", prevent, false);
		window.addEventListener("keyup", scanRequest, false);
		return () => {
			window.removeEventListener("keydown", prevent, false);
			window.removeEventListener("keyup", scanRequest, false);
		};
	}, []);

	// 阻止默认事件
	const prevent = e => {
		if (window.location.hash == "#/views/stock/scanEnterWarehouse") {
			if (["F1"].includes(e.key)) {
				e.preventDefault();
			}
		}
	};

	// 键盘事件监听
	const scanRequest = e => {
		if (window.location.hash == "#/views/stock/scanEnterWarehouse") {
			const { key } = e;
			switch (key) {
				case "F1":
					// 重置(F1)
					onReset();
					break;
				default:
					break;
			}
		}
	};

	// 扫描单号
	const getData = async code => {
		// setData(mock);
		// form.setFieldsValue({
		// 	warehouseName: mock.warehouseName,
		// 	warehouseId: mock.warehouseId,
		// 	warehouseType: mock.warehouseType,
		// 	code: null
		// });
		// RefCode.current.focus();
		const { success, data, msg } = await selectInboundorderDetailByCode({
			code
		});
		if (success) {
			if (!(Object.keys(data).length === 0)) {
				data.productInboundOrderDetailsList = data?.productInboundOrderDetailsList.map(e => {
					return {
						...e,
						actualNum: null
					};
				});

				setData(data);
				form.setFieldsValue({
					warehouseName: data.warehouseName,
					warehouseId: data.warehouseId,
					warehouseType: data.warehouseType,
					code: null
				});
				RefCode.current.focus();
			} else {
				message.error(msg);
			}
		} else {
			// message.warning("请检查单号是否正确");
		}
	};
	// 扫描条码
	const getCode = async code => {
		if (data?.productInboundOrderDetailsList?.length) {
			const skuData = data.productInboundOrderDetailsList.find(e => e.skuCode == code);
			if (skuData) {
				addShortageNum(skuData, code);
			} else {
				// 找不到，调用接口查询唯一码获取商品编码
				// code：唯一码
				const res = await getSkuCode({ code });
				const skuData = data.productInboundOrderDetailsList.find(e => e.skuCode == res.data);
				if (skuData) {
					addShortageNum(skuData, res.data);
				} else {
					// 找不到，弹出确定收货弹窗
					code && setVisible(true);
				}
			}
		}
	};

	// 增加入库数量逻辑
	function addShortageNum(skuData, code) {
		if (skuData) {
			setImgUrl(skuData.skuImage);
			setImgVisible(true);
			// 扫一个商品编码对应的商品入库数量加1时播报当前增加后的数值
			if (skuData.actualNum >= skuData.shortageNum) {
				form.setFieldsValue({
					code: null
				});
				return;
			}
			setData({
				...data,
				productInboundOrderDetailsList: data.productInboundOrderDetailsList.map(e => {
					if (e.skuCode == code) {
						// 播报当前增加后的数值
						isBroadcastScanQuantity && speak({ text: e.actualNum + 1 });
						return {
							...e,
							actualNum: Number(e.actualNum) + 1
						};
					}
					return e;
				})
			});
			form.setFieldsValue({
				code: null
			});
		}
	}

	// 重置
	const onReset = () => {
		setData({});
		setImgUrl();
		form.resetFields();
		RefNo.current.focus();
	};
	// 确认收货
	const onConfirmReceipt = async () => {
		if (!data.warehouseId) return message.warning("请选择入库仓库");
		if (data.productInboundOrderDetailsList.length === 0) return;
		// 若点击确认收货时，对应的入库总数量为0时，这里提示：请先填充入库数量。  入库都没填的时候点击不做处理 allEmpty判断是否全部为空 nonEmptyItems不为空的数据
		const { allEmpty, nonEmptyItems } = data.productInboundOrderDetailsList.reduce(
			(accumulator, item) => {
				if (item.actualNum) {
					accumulator.nonEmptyItems.push(item);
				}
				accumulator.allEmpty = accumulator.allEmpty && (item.actualNum === "" || item.actualNum === null);
				return accumulator;
			},
			{ allEmpty: true, nonEmptyItems: [] }
		);
		if (allEmpty) {
			message.warning("请先填充入库数量");
			return;
		}

		const API_DATA = {
			// 入库单号
			inboundOrder: data.inboundOrderNo,
			// 入仓仓库名称
			warehouseName: data.warehouseName,
			warehouseId: data.warehouseId,
			// 入仓仓库类型
			warehouseType: data.warehouseType,
			// 商品信息

			skuConfirmReceiptDTO: data.productInboundOrderDetailsList.map(e => {
				return {
					// 入库数量
					changeActualNum: e.actualNum || 0,
					skuId: e.skuId
				};
			})
		};
		// console.log("API_DATA", API_DATA);
		confirmReceipt(API_DATA).then(res => {
			const { success, data } = res;
			if (success) {
				message.success("确认收货成功");
				setVisible(false);
				setImgVisible(false);
				form.resetFields();
				setData({});
				RefNo.current.focus();
			} else {
				message.error("确认收货失败");
			}
		});
	};
	useEffect(() => {
		form.setFieldsValue({ data });
	}, [data]);
	useEffect(() => {
		RefNo.current.focus();
	}, []);
	return (
		<Form form={form}>
			<SubTitle symbol as="s3" title={<span className={Style.title}>扫码入仓</span>} wrapStyle={{ marginBottom: 16 }} />
			<Form.Item name="inboundOrderNo">
				<Input
					ref={RefNo}
					placeholder="请扫描/输入入库单/采购单"
					className={Style.height40}
					onPressEnter={e => {
						getData(e.target.value);
					}}
				/>
			</Form.Item>
			<Form.Item name="code">
				<Input
					ref={RefCode}
					placeholder="请扫描/输入商品编码/商品唯一码"
					onPressEnter={e => {
						getCode(e.target.value);
					}}
					className={"mt20 " + Style.height40}
				/>
			</Form.Item>
			<SubTitle
				symbol
				as="s3"
				title={<span className={Style.title}>入仓仓库</span>}
				wrapStyle={{ marginBottom: 16, marginTop: 20 }}
			/>
			<AntdWrapper label="发货仓" style={{ width: "100%", height: "40px" }}>
				<Form.Item name="warehouseId">
					<Select
						options={warehouseList}
						placeholder="请选择入库仓库"
						size="large"
						style={{ width: "100%" }}
						onSelect={(value, option) => {
							setData({
								...data,
								warehouseId: value,
								warehouseName: option.warehouseName,
								warehouseType: option.kind
							});
						}}
					/>
				</Form.Item>
			</AntdWrapper>
			<div className="flex justify-end mt20">
				<Button
					className={Style.height40}
					style={{ marginRight: 24 }}
					onClick={() => {
						onReset();
					}}
				>
					重置F1
				</Button>
				<Button className={Style.height40} type="primary" onClick={onConfirmReceipt}>
					确认收货
				</Button>
			</div>

			<SubTitle symbol as="s3" title="扫码设置" wrapStyle={{ marginBottom: 16, marginTop: 24 }} />

			<Checkbox
				checked={isShowImg}
				onChange={e => {
					setIsShowImg(e.target.checked);
				}}
			>
				<span className={Style.title}>扫描商品自动展示大图</span>
			</Checkbox>
			<div></div>
			<Checkbox
				checked={isBroadcastScanQuantity}
				onChange={e => {
					setIsBroadcastScanQuantity(e.target.checked);
				}}
				style={{ marginTop: 8 }}
			>
				<span className={Style.title}>播报扫描商品数量</span>
			</Checkbox>
			{visible && (
				<ConfirmModal
					onOk={() => {
						onConfirmReceipt();
					}}
					onCancel={() => {
						setVisible(false);
					}}
				/>
			)}
		</Form>
	);
};
export default Sider;
